package com.xcdh.base.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xcdh.commons.utils.UserContext;
import com.xcdh.domain.entity.DeptDO;
import com.xcdh.base.mapper.DeptMapper;
import com.xcdh.base.service.DeptService;
import com.xcdh.domain.entity.MenuDO;
import com.xcdh.domain.vo.*;
import com.xcdh.util.TreeUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, DeptDO> implements DeptService {

    @Override
    public List<ElTree<Long>> list(DeptDO deptDO) {
        UserVo user = UserContext.getUser();
        if(user.isAdmin()){
            List<DeptDO> list = lambdaQuery()
                    .like(StringUtils.isNotBlank(deptDO.getName()), DeptDO::getName, deptDO.getName())
                    .orderByDesc(DeptDO::getSortOrder)
                    .list();
            return buildTree(list) ;
        }
        List<DeptDO> list = lambdaQuery()
                .like(StringUtils.isNotBlank(deptDO.getName()), DeptDO::getName, deptDO.getName())
                .eq(DeptDO::getDeptId ,user.getDeptId())
                .orderByDesc(DeptDO::getSortOrder)
                .list();
        return buildTree(findChild(list)) ;
    }

    private List<DeptDO> findChild(List<DeptDO> list){
        List<String> ids = list.stream().map(DeptDO::getDeptId).collect(Collectors.toList());
        if(!ids.isEmpty()){
            List<DeptDO> children = lambdaQuery().in(DeptDO::getParentId, ids).list();
            list.addAll(findChild(children)) ;
        }
        return list ;
    }

    private List<ElTree<Long>> buildTree(List<DeptDO> list){
        List<DeptTreeVo> treeList = IntStream.range(0, list.size())
                .mapToObj(i -> {
                    DeptDO m = list.get(i);
                    DeptTreeVo vo = TypeValueA2B.a2b(m,DeptTreeVo.class) ;
                    vo.setIndex(i);
                    return vo;
                }) .collect(Collectors.toList());
        return TreeUtil.buildTree(treeList);
    }
}
